/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "VegetationManager.h"

namespace PQClient
{
	
	/** Just to locate palmiers with a pseudo-random algoritm
	 */
	float seed_ = 801;
	float rnd_(const float& min, const float& max)
	{
		seed_ += Ogre::Math::PI*2.8574f + seed_*(0.3424f - 0.12434f + 0.452345f);
		if (seed_ > 10000000000) seed_ -= 10000000000;
		return ((max-min)*Ogre::Math::Abs(Ogre::Math::Sin(Ogre::Radian(seed_))) + min);
	}


	VegetationManager::VegetationManager( PQEngine::SceneObject* sceneObject )
		: _sceneObject(sceneObject)
	{


		loadVegetation();

	}

	void VegetationManager::update( float deltaT )
	{

	}

	void VegetationManager::loadVegetation()
	{
		Ogre::SceneManager *mgr=_sceneObject->getSceneManager();

		const int NumberOfPalms = 12;
		for (int k = 0; k < NumberOfPalms; k++){
			Ogre::Vector3 RandomPos = Ogre::Vector3(rnd_(500,2500),0,rnd_(500,2500));

			Ogre::RaySceneQuery * raySceneQuery = mgr->createRayQuery(
				Ogre::Ray(RandomPos + Ogre::Vector3(0,1000000,0), 
				Ogre::Vector3::NEGATIVE_UNIT_Y));

			Ogre::RaySceneQueryResult& qryResult = raySceneQuery->execute();
			Ogre::RaySceneQueryResult::iterator i = qryResult.begin();

			if (i != qryResult.end() && i->worldFragment){
				if (i->worldFragment->singleIntersection.y>105 || i->worldFragment->singleIntersection.y<20){
					k--;
					continue;
				}
				RandomPos.y = i->worldFragment->singleIntersection.y;
			}else{
				k--;
				continue;
			}

			PQEngine::MeshObject* obj=_sceneObject->loadMeshObject("Palm.mesh");
			obj->rotate(Ogre::Vector3(-1,0,rnd_(-0.3,0.3)), Ogre::Degree(90));
			
			Ogre::Real Scale = rnd_(50,75);
			obj->scale(Ogre::Vector3(Scale,Scale,Scale));
			
			obj->setPosition(RandomPos);
		}
	}

}


